class SelectionSort {
    constructor() {
        this.numbers = [];
        this.isRunning = false;
        this.currentStep = 0;
        this.isAutoSorting = false;
        
        this.initializeElements();
        this.bindEvents();
        this.generateNumbers(); // 在构造函数中立即生成数字
    }

    initializeElements() {
        this.container = document.getElementById('numbersContainer');
        this.currentStepDisplay = document.getElementById('currentStep');
        this.generateNewBtn = document.getElementById('generateNew');
        this.startSortBtn = document.getElementById('startSort');
        this.nextStepBtn = document.getElementById('nextStep');
        this.resetBtn = document.getElementById('reset');
    }

    bindEvents() {
        this.generateNewBtn.addEventListener('click', () => this.generateNumbers());
        this.startSortBtn.addEventListener('click', () => this.startSort());
        this.nextStepBtn.addEventListener('click', () => this.nextStep());
        this.resetBtn.addEventListener('click', () => this.reset());
    }

    generateNumbers() {
        this.numbers = [];
        for (let i = 0; i < 6; i++) {
            this.numbers.push(Math.floor(Math.random() * 99) + 1);
        }
        this.reset();
        this.renderNumbers();
    }

    renderNumbers() {
        this.container.innerHTML = '';
        this.numbers.forEach((num, index) => {
            const box = document.createElement('div');
            box.className = 'number-box';
            box.textContent = num;
            if (index < this.currentStep) {
                box.classList.add('sorted');
            }
            this.container.appendChild(box);
        });
    }

    async startSort() {
        if (this.isRunning) return;
        this.isRunning = true;
        this.isAutoSorting = true;
        this.startSortBtn.disabled = true;
        this.generateNewBtn.disabled = true;
        this.nextStepBtn.disabled = true;

        for (let i = 0; i < this.numbers.length - 1; i++) {
            this.currentStep = i;
            await this.findAndSwapMin(i);
        }

        this.finishSort();
    }

    async findAndSwapMin(startIndex) {
        let minIdx = startIndex;
        const boxes = document.querySelectorAll('.number-box');

        boxes.forEach(box => box.classList.remove('searching', 'current-min'));
        boxes[minIdx].classList.add('current-min');
        
        this.currentStepDisplay.textContent = `从第 ${startIndex + 1} 个位置开始寻找最小值`;
        await new Promise(resolve => setTimeout(resolve, 500));

        for (let i = startIndex + 1; i < this.numbers.length; i++) {
            boxes.forEach(box => box.classList.remove('searching'));
            boxes[i].classList.add('searching');
            
            this.currentStepDisplay.textContent = 
                `比较：${this.numbers[i]} 和当前最小值 ${this.numbers[minIdx]}`;
            await new Promise(resolve => setTimeout(resolve, 500));

            if (this.numbers[i] < this.numbers[minIdx]) {
                boxes[minIdx].classList.remove('current-min');
                boxes[i].classList.add('current-min');
                minIdx = i;
                this.currentStepDisplay.textContent = `找到新的最小值：${this.numbers[minIdx]}`;
                await new Promise(resolve => setTimeout(resolve, 500));
            }
        }

        if (minIdx !== startIndex) {
            this.currentStepDisplay.textContent = 
                `交换 ${this.numbers[startIndex]} 和 ${this.numbers[minIdx]}`;
            await this.animateSwap(boxes[startIndex], boxes[minIdx]);
            [this.numbers[startIndex], this.numbers[minIdx]] = 
                [this.numbers[minIdx], this.numbers[startIndex]];
        }

        boxes[startIndex].classList.add('sorted');
        boxes[startIndex].classList.remove('current-min');
    }

    async animateSwap(element1, element2) {
        return new Promise(resolve => {
            const content1 = element1.textContent;
            const content2 = element2.textContent;
            
            element1.classList.add('swap-right');
            element2.classList.add('swap-left');

            const handleAnimationEnd = () => {
                element1.classList.remove('swap-right');
                element2.classList.remove('swap-left');
                
                element1.textContent = content2;
                element2.textContent = content1;
                
                element1.removeEventListener('animationend', handleAnimationEnd);
                resolve();
            };

            element1.addEventListener('animationend', handleAnimationEnd);
        });
    }

    async nextStep() {
        if (this.isAutoSorting) return;

        if (!this.isRunning) {
            this.isRunning = true;
            this.startSortBtn.disabled = true;
            this.generateNewBtn.disabled = true;
        }

        if (this.currentStep < this.numbers.length - 1) {
            await this.findAndSwapMin(this.currentStep);
            this.currentStep++;
        } else {
            this.finishSort();
        }
    }

    finishSort() {
        this.isRunning = false;
        this.isAutoSorting = false;
        this.startSortBtn.disabled = false;
        this.generateNewBtn.disabled = false;
        this.nextStepBtn.disabled = false;
        this.currentStepDisplay.textContent = '排序完成！';
        
        const boxes = document.querySelectorAll('.number-box');
        boxes.forEach(box => box.classList.add('sorted'));
    }

    reset() {
        this.currentStep = 0;
        this.isRunning = false;
        this.isAutoSorting = false;
        this.startSortBtn.disabled = false;
        this.generateNewBtn.disabled = false;
        this.nextStepBtn.disabled = false;
        this.currentStepDisplay.textContent = '准备开始...';
        this.renderNumbers();
    }
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', () => {
    new SelectionSort();
}); 